package com.systemic.service.impl;

import com.systemic.dto.SubjectDto;
import com.systemic.mapper.*;
import com.systemic.pojo.*;
import com.systemic.service.DynamicService;
import com.systemic.utils.FileUtils;
import com.systemic.vo.DynamicVo;
import com.systemic.vo.ImageInfoVo;
import com.systemic.vo.PageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.net.URL;
import java.util.*;

/**
 * @ClassName: DynamicServiceImpl
 * @Description:
 * @Author:
 * @CreateTime: 2024-01-05 13:57
 * @Version:
 **/
@Service
@PropertySource("classpath:/properties/image.properties")
public class DynamicServiceImpl implements DynamicService {

    @Resource
    private FriendMapper friendMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private DynamicImageMapper dynamicImageMapper;
    @Resource
    private SubjectMapper subjectMapper;
    @Resource
    private SubjectDynamicMapper subjectDynamicMapper;
    @Resource
    private LikeMapper likeMapper;

    @Value("${image.diUrl}")
    private String diUrl;
    @Value("${image.dynamicImage}")
    private String dynamicImagePath;        // 使用注解的方式定义文件地址

    // 状态值1 表示动态，用来执行查询
    private final Integer status = 1;

    /**
     * 发布动态
     *
     * @param images
     * @param dynamic
     * @param subject
     * @return
     */
    @Override
    @Transactional
    public int publish(MultipartFile[] images, Dynamic dynamic, Integer[] subject) {
        int row = 0;
        // 第一层判断：非空
        if (dynamic != null) {
            Date date = new Date();
            try {
                dynamic.setGmtCreate(date);
                dynamic.setGmtModified(date);
                row = dynamicMapper.insert(dynamic);
            } catch (Exception e) {
                throw new RuntimeException("新增dynamic错误" + e);
            }
            // 添加图片
            Integer id = dynamicMapper.getLastInsertId();   // 获取新增动态时数据表自增的主键
            int result = 0;
            if (images!=null){
                for (MultipartFile image : images) {

                    try {
                        System.out.println("开始上传图片");
                        String url = FileUtils.uploadImage(image, dynamicImagePath, diUrl);
                        System.out.println("图片URL为：" + url);
                        DynamicImage dynamicImage = new DynamicImage();
                        dynamicImage.setDid(id);    // 将动态主键设为该表的did属性
                        dynamicImage.setImage(url);  // 获取图片url
                        dynamicImage.setStatus(1);
                        row = dynamicImageMapper.insert(dynamicImage) + row;
                    } catch (Exception e) {
                        throw new RuntimeException("上传失败" + e);
                    }
                    result++; // 假设每次上传成功增加计数器
                }
                System.out.println("上传图片数量：" + result);
            } else {
                System.out.println("用户没有上传图片");
            }
            // TODO: 新增话题业务
            if (subject!=null){
                // 把话题id和动态id存储在关系表中
                for (Integer sid:subject) {
                    SubjectDynamic subjectDynamic = new SubjectDynamic();
                    subjectDynamic.setSid(sid); // 写入当前话题id
                    subjectDynamic.setDid(id);  // 写入当前动态id
                    subjectDynamic.setStatus(status);  //写入当前状态值
                    row = subjectDynamicMapper.insert(subjectDynamic) + row;
                }
            }
        }
        return row;
    }

    /**
     * 查看指定动态
     * @param dynamicVos
     * @return
     */
    @Override
    public DynamicVo selectById(DynamicVo dynamicVos) {
        Integer id = dynamicVos.getId();
        Integer uid = dynamicVos.getUid();
        // 根据前端传递的id查询动态信息
        Dynamic dynamic = dynamicMapper.selectById(id);
        DynamicVo dynamicVo = new DynamicVo();
        List<ImageInfoVo> imageInfoVos = new ArrayList<>();
        // 如果动态信息不为空
        if (dynamic != null) {
            Integer did = dynamic.getId();
            List<DynamicImage> dynamicImageList = dynamicImageMapper.selectListByDid(id, status);
            for (DynamicImage dynamicImage : dynamicImageList) {
                ImageInfoVo imageInfoVo = new ImageInfoVo();
                try {
                    imageInfoVo.setId(dynamicImage.getId());
                    imageInfoVo.setDid(dynamicImage.getDid());
                    imageInfoVo.setImage(dynamicImage.getImage());
                    imageInfoVo.setStatus(dynamicImage.getStatus());
                    imageInfoVos.add(imageInfoVo);
                } catch (Exception e) {
                    throw new RuntimeException("错误" + e);
                }
            }

            // 初始化
            List<SubjectDto> subjects = new ArrayList<>();
            SubjectDynamic subjectDynamic = new SubjectDynamic();
            // 根据动态id查询关联的话题
            subjectDynamic.setDid(did);
            subjectDynamic.setStatus(status);
            List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
            if (!subjectDynamics.isEmpty()){
                for (SubjectDynamic sub:subjectDynamics) {
                    //使用话题id（sid）做查询，再把sid和sname写入SubjectDto实体类
                    Subject subject = subjectMapper.selectById(sub.getSid());
                    if (subject!=null){
                        SubjectDto subjectDto = new SubjectDto();
                        subjectDto.setId(subject.getId());
                        subjectDto.setSname(subject.getSname());
                        subjects.add(subjectDto);
                    }
                }
            }
            // 判断是否为空
            if (!subjects.isEmpty()){
                dynamicVo.setSubjects(subjects);
            }

            Like like = new Like(null, did, uid);
            Like res = likeMapper.selectByDidAndUid(like);
            // 如果结果不为空，说明用户对当前动态点赞
            if (res!=null){
                dynamic.setIsLike(1);  // 1表示已点赞，类似你在朋友圈点赞一条动态后，点赞按钮处于点击状态
            }
            dynamicVo.setId(did);
            dynamicVo.setUid(dynamic.getUid());
            dynamicVo.setContent(dynamic.getContent());
            dynamicVo.setCommentNum(dynamic.getCommentNum());
            dynamicVo.setIsLike(dynamic.getIsLike());
            dynamicVo.setLikeNum(dynamic.getLikeNum());
            dynamicVo.setGmtCreate(dynamic.getGmtCreate());
            dynamicVo.setGmtModified(dynamic.getGmtModified());
            dynamicVo.setImages(imageInfoVos);
        }
        return dynamicVo;
    }

    /**
     * 修改动态
     * @param dynamic
     * @param images
     * @param subject
     * @return
     */
    @Override
    @Transactional
    public int update(Dynamic dynamic, MultipartFile[] images, Integer[] subject) {
        int row = 0;
        int res = 0;
        DynamicImage dynamicImage = new DynamicImage();
        if (dynamic != null) {
            Integer did = dynamic.getId();
            // 第一步：清除旧关联
            try {
                dynamicImage.setDid(did);
                dynamicImage.setStatus(status);
                //查询该动态是否有图片
                List<DynamicImage> dynamicImageList = dynamicImageMapper.selectList(dynamicImage);
                // 如果查询结果不为空执行
                if (!dynamicImageList.isEmpty()) {
                    for (DynamicImage image : dynamicImageList) {
                        try {
                            // url转换对应的本地路径
                            URL url = new URL(image.getImage());
                            String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                            if (FileUtils.delete(dynamicImagePath + fileName)) {
                                dynamicImageMapper.deleteById(image.getId());
                                System.out.println("删除成功");
                            } else {
                                System.out.println("文件不存在");
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("错误" + e);
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("错误" + e);
            }
            // 将文件上传本地
            if (images!=null){
                for (MultipartFile image : images) {
                    try {
                        String imageUrl = FileUtils.uploadImage(image, dynamicImagePath, diUrl);
                        DynamicImage dynamicImg = new DynamicImage();
                        dynamicImg.setDid(did);
                        dynamicImg.setImage(imageUrl);  // 获取图片url
                        dynamicImg.setStatus(status);
                        row = dynamicImageMapper.insert(dynamicImg) + row;
                    } catch (Exception e) {
                        throw new RuntimeException("上传失败" + e);
                    }
                    res++; // 假设每次上传成功增加计数器
                }
                System.out.println("上传图片数量：" + res);
            }

            // 先根据did和status查询有哪些话题，使用List接收
            SubjectDynamic subjectDynamic = new SubjectDynamic();
            subjectDynamic.setDid(did);
            subjectDynamic.setStatus(status);
            List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
            // 对list遍历，每次执行删除操作
            if (!subjectDynamics.isEmpty()){
                for (SubjectDynamic sub:subjectDynamics) {
                    row = subjectDynamicMapper.delete(sub) + row;
                }
            }
            //第二步：建立新关联
            if (subject!=null){
                // 把话题id和动态id存储在关系表中
                for (Integer sid:subject) {
                    SubjectDynamic sub = new SubjectDynamic();
                    sub.setSid(sid); // 写入当前话题id
                    sub.setDid(did);  // 写入当前动态id
                    sub.setStatus(status);  //写入当前状态值
                    row = subjectDynamicMapper.insert(sub) + row;
                }
            }
            // 更新数据库记录
            dynamic.setGmtModified(new Date());
            row = dynamicMapper.update(dynamic) + row;
        }
        return row;
    }

    /**
     * 删除动态
     * @param dynamic
     * @return
     */
    @Override
    @Transactional
    public int delete(Dynamic dynamic) {
        int row = 0;
        DynamicImage dynamicImage = new DynamicImage();
        Integer did = dynamic.getId();
        try{
            dynamicImage.setDid(did);
            dynamicImage.setStatus(status);
            // TODO: 根据 dynamicImage的信息查询本地待删除的图片
            List<DynamicImage> dynamicImageList = dynamicImageMapper.selectList(dynamicImage);
            if (dynamicImageList!=null){
                for (DynamicImage image:dynamicImageList) {
                    // url转换对应的本地路径
                    URL url = new URL(image.getImage());
                    String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                    if (FileUtils.delete(dynamicImagePath + fileName)){
                        // 删除草稿关联的图片数据记录
                        dynamicImageMapper.deleteById(image.getId());
                    }else{
                        System.out.println("文件不存在");
                    }
                }
            }
        }catch(Exception e){
            throw new RuntimeException("错误" + e);
        }

        // 先根据did和status查询有哪些话题，使用List接收
        SubjectDynamic subjectDynamic = new SubjectDynamic();
        subjectDynamic.setDid(did);
        subjectDynamic.setStatus(status);
        List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
        // 对list遍历，每次执行删除操作
        if (!subjectDynamics.isEmpty()){
            for (SubjectDynamic sub:subjectDynamics) {
                row = subjectDynamicMapper.delete(sub) + row;
            }
        }
        row = dynamicMapper.delete(dynamic);
        if (row==0){
            throw new RuntimeException("删除草稿失败");
        }
        return row;
    }

    /**
     * 管理端：批量删除
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int deleteList(Integer[] ids) {
        int row = 0;
        // 将数组转换为集合
        List<Integer> idList = Arrays.asList(ids);
        // 批量删除动态
        row = dynamicMapper.deleteBatchIds(idList);
        // TODO: 批量删除动态关联的图片
        for (Integer id:idList) {
            // 删除动态关联的图片
            row = dynamicImageMapper.deleteByDidAndStatus(id, status) + row;
            // 删除动态关联的话题
            // 先根据did和status查询有哪些话题，使用List接收
            SubjectDynamic subjectDynamic = new SubjectDynamic();
            subjectDynamic.setDid(id);
            subjectDynamic.setStatus(status);
            List<SubjectDynamic> subjectDynamics = subjectDynamicMapper.select(subjectDynamic);
            // 对list遍历，每次执行删除操作
            if (!subjectDynamics.isEmpty()){
                for (SubjectDynamic sub:subjectDynamics) {
                    row = subjectDynamicMapper.delete(sub) + row;
                }
            }
        }
        return row;
    }

    /**
     * 客户端：动态分页查询
     * “偏移量分页”查询方式
     * @param pageVo
     * @return
     */
    @Override
    public List<Dynamic> selectList(PageVo pageVo) {
        // 获取当前页数和每页显示的数据条数
        Integer pageNo = pageVo.getPageNo();
        Integer pageSize = pageVo.getPageSize();
        // 计算OFFSET值
        Integer offset = (pageNo - 1) * pageSize;
        // 先拿到用户id
        Integer uid = pageVo.getUid();
        // 先查询用户的动态
        List<Dynamic> dynamics = dynamicMapper.selectListByUidPage(uid, offset, pageSize);
        // 根据uid查询用户有哪些联系人
        List<Friend> friends = friendMapper.selectListById(uid);
        for (Friend friend:friends) {
            // 根据好友id查询好友的动态
            List<Dynamic> dynamicList = dynamicMapper.selectListByUidPage(friend.getFid(), offset, pageSize);
            dynamics.addAll(dynamicList);
        }
        List<Dynamic> dynamicList = new ArrayList<>();
        // 查询动态关联的图片
        // TODO:查询动态关联的点赞，确保正常显示当前用户是否已经点赞
        for (Dynamic dynamic:dynamics) {
            Integer did = dynamic.getId();
            Like like = new Like(null, did, uid);
            Like res = likeMapper.selectByDidAndUid(like);
            // 如果结果不为空，说明用户对当前动态点赞
            if (res!=null){
                dynamic.setIsLike(1);  // 1表示已点赞，类似你在朋友圈点赞一条动态后，点赞按钮处于点击状态
            }
            DynamicImage dynamicImage = dynamicImageMapper.selectByDid( did, status);
            if (dynamicImage!=null){
                dynamic.setDynamicImage(dynamicImage);
                dynamicList.add(dynamic);
            }else{
                dynamicList.add(dynamic);
            }
        }
        return dynamicList;
    }


    /**
     * 管理端：动态分页查询
     * @param pageVo
     * @return
     */
    @Override
    public List<Dynamic> getList(PageVo pageVo) {
        // 获取当前页数和每页显示的数据条数
        Integer pageNo = pageVo.getPageNo();
        Integer pageSize = pageVo.getPageSize();
        // 计算OFFSET值
        Integer offset = (pageNo - 1) * pageSize;
        List<Dynamic> dynamics = dynamicMapper.selectListPage(offset, pageSize);

        // TODO:查询动态关联的图片
        List<Dynamic> dynamicList = new ArrayList<>();
        for (Dynamic dynamic:dynamics) {
            DynamicImage dynamicImage = dynamicImageMapper.selectByDid(dynamic.getId(), status);
            if (dynamicImage!=null){
                dynamic.setDynamicImage(dynamicImage);
                dynamicList.add(dynamic);
            }else{
                dynamicList.add(dynamic);
            }
        }
        return dynamicList;
    }

}
